
package com.multimedia.room;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.text.TextUtils;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class CommonUtil {
    private static final boolean DEBUG = false;
    private static final String TAG = "CommonUtil";
    public static final String USER_NAME_KEY = "username";
    public static final String SEATNO = "seatno";
    public static final String CONFID_IP = "config_ip";
    public static final String RE_INIT = "re_init";
    public static final String IP_PRIFEX = "prefix";
    public static final String GATEWAYSTRING_ENDS = "gateway_ends";
    public static final String HAS_KILLED = "has_killed";
    public static final String KILL_TIMES = "kill_times";
    public static final String USER_PASSWORD_KEY = "password";
    private static SharedPreferences mSharedPreferences;
    private static final CommonUtil INSTANCE = new CommonUtil();
    private static Context sContext;
    private static final String INTERNAL_CONFIG_FILE_NAME = "config.cg";
    public static final String CHARSET_UTF_8 = "UTF-8";
    public static final String CHARSET_GBK = "GBK";
    public static final String THEME_KKEY="theme_key";

    public static final String[] sSeatPrefix = {
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q",
            "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
    };
    public static final String[] sSeatsuffix = {
            "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13","14", "15", "16", "17",
            "18", "19", "20"
    };
    //视频广播gpio
    //./arch/arm/mach-sunxi/include/mach/gpio.h
//    /pinctrl/pinctrl-sunxi.h
    //PG11, PG12 , PG13
    private static final String GPIO203_FILE = "/sys/class/gpio/gpio203/value";
    private static final String GPIO204_FILE = "/sys/class/gpio/gpio204/value";
    private static final String GPIO205_FILE = "/sys/class/gpio/gpio205/value";

    //PC PL2, PL6 , PL10
    private static final String GPIO354_FILE = "/sys/class/gpio/gpio354/value";
    private static final String GPIO358_FILE = "/sys/class/gpio/gpio358/value";
    private static final String GPIO362_FILE = "/sys/class/gpio_sw/PL10/data";


    //网卡gpio
    private static final String GPIO363_FILE="/sys/class/gpio/gpio363/value";
    private static final String GPIO_MODE = "gpio_mode";
    //local
    private static final String GPIO_LOCAL_MODE = "101111";
    //remote
    private static final String GPIO_REMOTE_MODE = "010111";
    //pc
    private static final String GPIO_PC_MODE = "000000";




    public static final String APP_THEME_DEFAULT="theme_default";
    public static final String APP_THEME_1="theme_1";
    public static final String APP_THEME_2="theme_2";
    public static final String APP_THEME_3="theme_3";
    private CommonUtil() {

    }

    public static String getSeatNo() {
        return mSharedPreferences.getString(SEATNO, "A1");
    }

    public static String getIpPrefix() {
        return mSharedPreferences.getString(IP_PRIFEX, "192.168.1");
    }

    public static void setIpPrefix(String prefix) {
        Editor editor = mSharedPreferences.edit();
        editor.putString(IP_PRIFEX, prefix);
        editor.commit();
    }
    
    public static boolean isConfigIP() {
        return mSharedPreferences.getBoolean(CONFID_IP, false);
    }
    
    public static void configIP(boolean flag) {
    	Editor editor = mSharedPreferences.edit();
        editor.putBoolean(CONFID_IP, flag);
        editor.commit();
    }

    public static void configGATEWAY(int gateway) {
        Editor editor = mSharedPreferences.edit();
        editor.putInt(GATEWAYSTRING_ENDS, gateway);
        editor.commit();
    }
    public static int getGateWay() {
        return mSharedPreferences.getInt(GATEWAYSTRING_ENDS, 1);
    }
    public static void setHasKilled(boolean killed) {
        Editor editor = mSharedPreferences.edit();
        editor.putBoolean(HAS_KILLED, killed);
        editor.commit();
    }
    public static boolean hasKilled() {
        return mSharedPreferences.getBoolean(HAS_KILLED, true);
    }

    public static void setKillTimes(int time) {
        Editor editor = mSharedPreferences.edit();
        editor.putInt(KILL_TIMES, time);
        editor.commit();
    }
    public static int getKillTimes() {
        return mSharedPreferences.getInt(KILL_TIMES, 0);
    }

    public static boolean isReInit() {
        return mSharedPreferences.getBoolean(RE_INIT, false);
    }
    
    public static void configReInit(boolean flag) {
    	Editor editor = mSharedPreferences.edit();
        editor.putBoolean(RE_INIT, flag);
        editor.commit();
    }
    

    public static void setTheme(String theme){
        Editor editor = mSharedPreferences.edit();
        editor.putString(THEME_KKEY, theme);
        editor.commit();
    }

    public static String getTheme(){
        return mSharedPreferences.getString(THEME_KKEY, APP_THEME_DEFAULT);
    }
    public static synchronized CommonUtil getInstance(Context context) {
            sContext = context;
            mSharedPreferences = sContext.getSharedPreferences(
                    INTERNAL_CONFIG_FILE_NAME, Context.MODE_PRIVATE);
        return INSTANCE;
    }

    public static String getValueFromSharePreferences(String key) {
        return mSharedPreferences.getString(key, "");
    }

    public static void reStoreValueIntoSharePreferences(String key, String value) {
        Editor editor = mSharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

    public static boolean checkSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    public static void showDialog(Context context, int resId, int msgId) {
        new AlertDialog.Builder(context).setTitle(resId).setMessage(msgId)
                .setPositiveButton(R.string.ok, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                    }
                }).create().show();
    }
    
   public static void showDialog(Context context, String title, String message) {
		new AlertDialog.Builder(context).setTitle(title).setMessage(message)
				.setPositiveButton(R.string.ok, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                    }
                }).create().show();
	}

    public static void showCustomDialog(Context context, View view,
            String title, DialogInterface.OnClickListener listener) {
        new AlertDialog.Builder(context).setView(view).setTitle(title)
                .setPositiveButton(R.string.ok, listener).create().show();
    }


    
    public static void showCustomDialog(Context context, int width ,View view,
            String title, DialogInterface.OnClickListener listener) {
        AlertDialog dialog = new AlertDialog.Builder(context).setView(view).setTitle(title)
                .setPositiveButton(R.string.ok, listener).create();
        dialog.show();
        WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
        layoutParams.width = width;
        layoutParams.height = LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(layoutParams);
    }

    public static AlertDialog  showWarnDialog(Context context, String title,
            String msg, OnClickListener oklistener, OnClickListener cancellistener) {
        return new AlertDialog.Builder(context).setTitle(title).setMessage(msg)
                .setPositiveButton(R.string.ok, oklistener)
                .setNegativeButton(R.string.cancel, cancellistener).create();
    }

    public static void showSelectedDialog(Context context) {
        final String[] items = new String[]{"默认主题", "主题1", "主题2", "主题3"};

        new AlertDialog.Builder(context)
                .setItems(items, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String theme = APP_THEME_DEFAULT;
                        if (0 == i) {
                            CommonUtil.setTheme(CommonUtil.APP_THEME_DEFAULT);
                            theme = APP_THEME_DEFAULT;
                        } else if (1 == i) {
                            CommonUtil.setTheme(CommonUtil.APP_THEME_1);
                            theme = APP_THEME_1;
                        } else if (2 == i) {
                            CommonUtil.setTheme(CommonUtil.APP_THEME_2);
                            theme = APP_THEME_2;
                        } else if (3 == i) {
                            CommonUtil.setTheme(CommonUtil.APP_THEME_3);
                            theme = APP_THEME_3;

                        }
                        Toast.makeText(sContext, "select " + i + " theme " + theme, 2).show();

                    }
                }).create()
                .show();
    }

    public static String convertStreamToString(InputStream is, String charset) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is, charset),
                    512 * 1024);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            Log.e("DataProvier convertStreamToString", e.getLocalizedMessage(),
                    e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static String getData(String url, String charSet){
        String result = "";
        while (TextUtils.isEmpty(result)) {
        	Log.d("result", result +"=====");
        HttpGet httpGet = new HttpGet(url);
        
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,6000);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,6000);
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String charset = EntityUtils.getContentCharSet(httpEntity);
            Log.d("Charset", "charset= " + charset);
            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                result = convertStreamToString(inputStream, charSet);

            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        }
        return result;

    }

    public static String convertTime(long mis) {
        int time = (int) (mis / 1000);
        StringBuilder sb = new StringBuilder();
        int leftseconds = time % 60;
        int minutes = time / 60;
        int leftMinutes = minutes % 60;
        int hour = minutes / 60;

        if (hour < 10) {
            sb.append("0").append(hour).append(":");
        } else {
            sb.append("0").append(hour).append(":");
        }
        if (minutes < 10) {
            sb.append("0").append(leftMinutes).append(":");
        } else {
            sb.append(leftMinutes).append(":");
        }
        if (leftseconds < 10) {
            sb.append("0").append(leftseconds);
        } else {
            sb.append(leftseconds);
        }

        return sb.toString();
    }

    public static String getFileData(String url)
             {
        String result = "";
        while(TextUtils.isEmpty(result)){
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = null;
	     Log.d("httpResponse", httpResponse!=null?"not null":"is null");
        try {
            httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                result = convertStreamToString(inputStream, CHARSET_GBK);

            }
        } catch (ClientProtocolException e) {
             httpResponse = null;
             e.printStackTrace();
        } catch (IOException e) {
            httpResponse = null;
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        }
        return result;

    }

    public static String getDataFromUrl(String url)
    {
        String result = "";
            HttpGet httpGet = new HttpGet(url);
            HttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//连接时间
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//数据传输时间
            HttpResponse httpResponse = null;
            try {
                httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null) {
                    InputStream inputStream = httpEntity.getContent();
                    result = convertStreamToString(inputStream, CHARSET_GBK);

                }
            } catch (ClientProtocolException e) {
                httpResponse = null;
                e.printStackTrace();
            } catch (IOException e) {
                httpResponse = null;
                e.printStackTrace();
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        return result;

    }

    public static ArrayList<FilesEntity> getFilesEntityFromJson(
            String result) throws JSONException {
        ArrayList<FilesEntity> files = new ArrayList<FilesEntity>();// 初始化files集合
        FilesEntity file = null;
        JSONObject rootJson = new JSONObject(result);
        JSONArray fileJsonArray = rootJson.getJSONArray("Files");
        for (int i = 0; i < fileJsonArray.length(); i++) {
            JSONObject jo = fileJsonArray.getJSONObject(i);
            String url = jo.getString("FileUrl");
            String type = jo.getString("FileExtension");
            String name = jo.getString("FileName");
            Log.d("file", "url " + url + " type " + type + " name "
                    + name);
            file = new FilesEntity();
            file.setUrl(url);// 得到file标签的属性值，并设置file的url
            file.setType(type);
            file.setName(name);
            files.add(file);
        }
        return files;
    }

    public static ArrayList<FilesEntity> getFilesEntityFromXML(
            InputStream inputStream) {
        ArrayList<FilesEntity> files = null;

        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(inputStream, CHARSET_UTF_8);
            int event = parser.getEventType();// 产生第一个事件
            while (event != XmlPullParser.END_DOCUMENT) {
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:// 判断当前事件是否是文档开始事件
                        files = new ArrayList<FilesEntity>();// 初始化files集合
                        break;
                    case XmlPullParser.START_TAG:// 判断当前事件是否是标签元素开始事件
                        Log.d("start_tag", parser.getName());
                        if ("file".equals(parser.getName())) {// 判断开始标签元素是否是file
                            FilesEntity file = new FilesEntity();
                            String url = parser.getAttributeValue(0);
                            String type = parser.getAttributeValue(1);
                            String name = parser.nextText();
                            Log.d("file", "url " + url + " type " + type + " name "
                                    + name);
                            file.setUrl(url);// 得到file标签的属性值，并设置file的url
                            file.setType(type);
                            file.setName(name);
                            files.add(file);
                            Log.d("file", files.toString());
                        }

                        break;
                    case XmlPullParser.END_TAG:// 判断当前事件是否是标签元素结束事件
                        Log.d("end_tag", parser.getName());
                        break;
                }
                event = parser.next();// 进入下一个元素并触发相应事件
            }// end while
        } catch (Exception ex) {
            Log.d("purser error", "parser xml error!", ex);
        }
        return files;

    }
    

	public static MediaMessage parseMessage(String content) {
		MediaMessage message = null;
		try {
			JSONObject jsonStr = new JSONObject(content);
			String tpye = jsonStr.getString("type");
			String receiver = jsonStr.getString("receiver");
			String mode = jsonStr.getString("mode");
			String command = jsonStr.getString("command");
			String group = jsonStr.getString("group");
			String param = jsonStr.getString("param");

			message = new MediaMessage(tpye, receiver, mode, command, group,
					param);
			if(DEBUG){
			Log.d("message", "message +" + message.toString());
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
            Log.e("message", "message ", e);
		}

		return message;
	}

    // 101
    public static void sendLocalVGAOut() {
        String mode = mSharedPreferences.getString(GPIO_MODE, "");
         Log.i(TAG,"sendLocalVGAOut : current mode "+mode);
        if (mode.equals(GPIO_LOCAL_MODE)) {
            Log.d(TAG, "gpio has set , doesn't need set it again");
        } else {
            setGPIOVaule(GPIO203_FILE, 1);
            setGPIOVaule(GPIO204_FILE, 0);
            setGPIOVaule(GPIO205_FILE, 1);
            setGPIOVaule(GPIO354_FILE, 1);
            setGPIOVaule(GPIO358_FILE, 1);
            setGPIOVaule(GPIO362_FILE, 1);
            mSharedPreferences.edit().putString(GPIO_MODE,GPIO_LOCAL_MODE).commit();
        }
    }
    
    public static void resetEthoGpio(int value){
    	 if (!isExists(GPIO363_FILE)) {
             return;
         }
    	String cmd = "echo " + value + " > " + GPIO363_FILE;
        Log.d(TAG, "cmd "+cmd);
        ShellUtils.execCommand(cmd, false);
    }

    //010
    public static void sendRemoteVGAOut() {
        String mode = mSharedPreferences.getString(GPIO_MODE, "");
        Log.i(TAG," sendRemoteVGAOut: current mode "+mode);
        if (mode.equals(GPIO_REMOTE_MODE)) {
            Log.d(TAG, "gpio has set , doesn't need set it again");
        } else {
            setGPIOVaule(GPIO203_FILE, 0);
            setGPIOVaule(GPIO204_FILE, 1);
            setGPIOVaule(GPIO205_FILE, 0);
            setGPIOVaule(GPIO354_FILE, 1);
            setGPIOVaule(GPIO358_FILE, 1);
            setGPIOVaule(GPIO362_FILE, 1);
            mSharedPreferences.edit().putString(GPIO_MODE,GPIO_REMOTE_MODE).commit();
        }
    }

    //010
    public static void sendLOCALPCOut() {
        String mode = mSharedPreferences.getString(GPIO_MODE, "");
        Log.i(TAG," sendLOCALPCOut: current mode "+mode);
        if (mode.equals(GPIO_PC_MODE)) {
            Log.d(TAG, "gpio has set , doesn't need set it again");
        } else {
            setGPIOVaule(GPIO203_FILE, 0);
            setGPIOVaule(GPIO204_FILE, 0);
            setGPIOVaule(GPIO205_FILE, 0);
            setGPIOVaule(GPIO354_FILE, 0);
            setGPIOVaule(GPIO358_FILE, 0);
            setGPIOVaule(GPIO362_FILE, 0);
            mSharedPreferences.edit().putString(GPIO_MODE,GPIO_PC_MODE).commit();
        }
    }

    public static int getGPIOVaule(String path) {
        if (!isExists(path)) {
            return 0;
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(path));
            String tempString = null;
            int line = 1;
            while ((tempString = reader.readLine()) != null) {
                Log.d(TAG, path + "pkg name : " + line + "   " + tempString);
                // The second line is recovery status -- 0: fail, 1:success
                if (line == 1) {
                    Log.d(TAG, path + " status : " + " " + line + tempString);
                    return Integer.parseInt(tempString);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return 1;
    }

    public static void setGPIOVaule(String path, int value) {
        if (!isExists(path)) {
            return;
        } else {
            if (value == getGPIOVaule(path)) {
                Log.d(TAG, "the value " + value + "has set");
            }
                String cmd = "echo " + value + " > " + path;
                Log.d(TAG, "cmd "+cmd);
                ShellUtils.execCommand(cmd, false);
        }

    }

    public static void changeMode(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        } else {

            String cmd = "chmod 777 -R " + path;
            Log.d(TAG, "cmd "+cmd);
            ShellUtils.execCommand(cmd, false);
        }

    }

    public static void execCommand(String command) throws IOException {  
        // start the ls command running  
        //String[] args =  new String[]{"sh", "-c", command};  
        Runtime runtime = Runtime.getRuntime(); 
        runtime.exec("sh");
        Process proc = runtime.exec(command);        //这句话就是shell与高级语言间的调用  
            //如果有参数的话可以用另外一个被重载的exec方法  
            //实际上这样执行时启动了一个子进程,它没有父进程的控制台  
            //也就看不到输出,所以我们需要用输出流来得到shell执行后的输出  
            InputStream inputstream = proc.getInputStream();  
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);  
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);  
            // read the ls output  
            String line = "";  
            StringBuilder sb = new StringBuilder(line);  
            while ((line = bufferedreader.readLine()) != null) {  
                //System.out.println(line);  
                    sb.append(line);  
                    sb.append('\n');  
            }  
            //tv.setText(sb.toString());  
            //使用exec执行不会等执行成功以后才返回,它会立即返回  
            //所以在某些情况下是很要命的(比如复制文件的时候)  
            //使用wairFor()可以等待命令执行完成以后才返回  
            try {  
                if (proc.waitFor() != 0) {  
                    System.err.println("exit value = " + proc.exitValue());  
                }  
            }  
            catch (InterruptedException e) {    
                System.err.println(e);  
            }  
        }  



    public static boolean isExists(String path) {
        File file = new File(path);
        if (file.exists()) {
            Log.d(TAG, "file is exit for " + path);
            return true;
        } else {
            Log.d(TAG, "file is not exit for " + path);
            return false;
        }
    }

    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除指定文件夹下所有文件
//param name 文件夹完整绝对路径
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }


}
